<template>
   <el-card class="purchase-card">
    <template #header>
      <div class="card-header">
        <span class="card-title">采购订单列表</span>
                <!-- 状态筛选按钮组 -->
                <div class="filter-buttons">
          <el-button-group>
            <el-button @click="filterStatus('all')">全部</el-button>
            <el-button @click="filterStatus('待采购')">待采购</el-button>
            <el-button @click="filterStatus('待审核')">待审核</el-button>
            <el-button @click="filterStatus('审核不通过')">审核不通过</el-button>
            <el-button @click="filterStatus('待入库')">待入库</el-button>
          </el-button-group>
        </div>

        <!-- 搜索框 -->
        <!-- <el-input 
          v-model="searchKeyword" 
          placeholder="搜索订单编号/商品ID" 
          style="width: 200px;"
          @keyup.enter="handleSearch"
        /> -->
      </div>
    </template>
    <!-- 饼图与创建按钮行 -->
    <el-row :gutter="20" class="chart-action-row">
      <!-- 饼图（左） -->
      <el-col :span="16">
        <div class="chart-container" style="width: 100%; height: 300px; position: relative;">
    <VChart 
      :option="chartOption" 
      v-if="statusStatistics.length > 0"
      :autoresize="true"
    />
  </div>
      </el-col>

      <!-- 创建按钮（右） -->
      <el-col :span="8" class="create-btn-col">
        <div class="create-btn-wrapper">
          <el-button type="primary" @click="createDialogVisible = true">创建采购订单</el-button>
        </div>
      </el-col>
    </el-row>
  <div class="purchase-manage-container">

    <!-- 采购订单列表 -->
    <el-table 
      :data="currentPageData" 
      border 
      stripe 
      fit  
      style="width: 100%; margin-top: 20px"
    >
      <!-- 订单编号：调整为min-width避免过窄 -->
      <el-table-column prop="number" label="订单编号" min-width="140" />
      <!-- 商品ID：使用ellipsis省略长文本 -->
      <el-table-column prop="productId" label="商品ID" min-width="210" show-overflow-tooltip />
      <!-- 采购数量：固定宽度 -->
      <el-table-column prop="quantity" label="采购数量" width="100" />
      <!-- 供应商：调整为min-width -->
      <el-table-column prop="supplier" label="供应商" min-width="180" />
      <!-- 采购地区：固定宽度 -->
      <el-table-column prop="area" label="采购地区" width="120" />
      <!-- 状态：固定宽度 -->
      <el-table-column prop="status" label="订单状态" width="150">
        <template #default="scope">
          <el-tag :type="statusMap[scope.row.status].type">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 操作列：固定宽度 -->
      <el-table-column label="操作" min-width="400">
        <template #default="scope">
          <!-- 待审核状态显示审核按钮 -->
          <el-button 
            v-if="scope.row.status === '待审核'" 
            type="info" 
            size="small"
            @click="showApproveDialog(scope.row._id)"
          >审核</el-button>
          <template  v-if="scope.row.status === '审核不通过'" > 
            <el-button type="warning" size="small" @click="handleReSubmit(scope.row._id)">重新提交</el-button>
            <el-button type="danger" size="small" @click="handleCancel(scope.row._id)">取消订单</el-button>
          </template>
          <!-- 待采购/采购中状态显示完成采购按钮 -->
          <el-button 
            v-if="['待采购','采购中'].includes(scope.row.status)" 
            type="success" 
            size="small"
            @click="handleComplete(scope.row._id)"
          >完成采购</el-button>
          <!-- 订单详情 -->
          <el-button type="text" size="small" @click="handleDetail(scope.row._id)">
            订单详情            
          </el-button>

        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
    <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next, jumper, ->, total"
      @current-change="handleCurrentChange"
      style="margin-top: 20px;"
    />
    </div>
    <!-- 创建订单对话框 -->
    <el-dialog 
      title="创建采购订单" 
      v-model="createDialogVisible"
      width="50%"
    >
      <el-form ref="createFormRef" :model="createForm" :rules="createRules" label-width="100px">
        <el-form-item label="采购地区" prop="area">
          <el-input v-model="createForm.area" placeholder="请输入采购地区（如：华东区）" />
        </el-form-item>
        <el-form-item label="订单编号" prop="number">
          <el-input v-model="createForm.number" placeholder="请输入唯一订单编号（如：PO20240801001）" />
        </el-form-item>
        <el-form-item label="商品ID" prop="productId">
          <el-input v-model="createForm.productId" placeholder="请输入商品MongoDB ID" />
        </el-form-item>
        <el-form-item label="采购数量" prop="quantity">
          <el-input-number v-model="createForm.quantity" min="1" placeholder="请输入采购数量" />
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-input v-model="createForm.supplier" placeholder="请输入供应商名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">提交</el-button>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog 
      title="审核采购订单" 
      v-model="approveDialogVisible"
      width="30%"
    >
      <p>确定要审核当前采购订单吗？</p>
      <template  #footer >
        <div style="display: flex; justify-content: space-between; width: 100%;">   
        <el-button type="danger" @click="handleReject">不通过</el-button>
        <el-button type="success" @click="handleApprove">通过</el-button>
      </div>
      </template>
    </el-dialog>
  </div>
</el-card>
</template>

<script setup>
import { ref, reactive, onMounted,computed } from 'vue'
import { ElMessage, ElDialog } from 'element-plus'
import { purchaseApi } from '@/api/purchase'
import { defineOptions } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
use([
  CanvasRenderer,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent
])
// 状态颜色映射（待审核: 蓝色，审核不通过: 红色，待采购: 绿色，采购中: 橙色，待入库: 紫色）
const statusMap = {
  '待审核': { type: 'info' },
  '审核不通过': { type: 'danger' },
  '待采购': { type: 'success' },
  '采购中': { type: 'warning' },
  '待入库': { type: 'primary' },
  '已取消':{ type: 'danger' },
  '采购完成':{ type: 'success' }
} 

// 订单列表数据
const purchaseOrders = ref([])

// 创建订单相关
const createDialogVisible = ref(false)
const createForm = reactive({
  area: '',
  number: '',
  productId: '',
  quantity: 1,
  supplier: ''
})
const createRules = {
  area: [{ required: true, message: '请输入采购地区', trigger: 'blur' }],
  number: [{ required: true, message: '请输入订单编号', trigger: 'blur' }],
  productId: [{ required: true, message: '请输入商品ID', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入采购数量', trigger: 'blur' }],
  supplier: [{ required: true, message: '请输入供应商', trigger: 'blur' }]
}
const createFormRef = ref(null)

// 审核相关
const approveDialogVisible = ref(false)
const currentOrderId = ref('')


const currentPage = ref(1)  // 当前页（初始为1）
const pageSize = ref(10)    // 每页显示10条（固定值）
const total = ref(0)        // 总数据量（等于purchaseOrders长度）

// 计算当前页数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filterOrders.value.slice(start, end)  // 切片获取当前页数据
})
//过滤出待采购，采购中，待入库
import { useRouter } from 'vue-router'
const router = useRouter()
const handleDetail = (orderId) => {
  router.push(`purchaseOrderDetail/${orderId}`)

}
const filterOrders =ref([])
const filterStatus = (status) => {
  console.log(status);
  console.log(purchaseOrders.value);
  
  if (status === 'all') {
    filterOrders.value = purchaseOrders.value
  } else {
    filterOrders.value = purchaseOrders.value.filter(order => order.status === status)
  }
}
// 状态统计计算属性
const statusStatistics = computed(() => {
  const stats = {}
  purchaseOrders.value.forEach(order => {
    stats[order.status] = (stats[order.status] || 0) + 1
  })
  return Object.entries(stats).map(([status, value]) => ({
    value,
    name: status,
    itemStyle: { 
      color: getStatusColor(status) // 使用统一颜色获取方法
    }
  }))
})
// 状态颜色映射
const getStatusColor = (status) => {
  const type = statusMap[status]?.type
  switch(type) {
    case 'info': return '#409EFF' // 蓝色
    case 'danger': return '#F56C6C' // 红色
    case 'success': return '#67C23A' // 绿色
    case 'warning': return '#E6A23C' // 橙色
    case 'primary': return '#909399' // 灰色
    default: return '#909399' // 默认灰色
  }
}
// 图表配置
const chartOption = computed(() => ({
  title: {
    text: '采购订单状态分布',
    left: 'center'
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    data: statusStatistics.value.map(item => item.name)
  },
  series: [{
    name: '状态分布',
    type: 'pie',
    radius: '50%',
    data: statusStatistics.value,
    emphasis: {
      itemStyle: {
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)'
      }
    }
  }]
}))
// 分页切换
const handleCurrentChange = (val) => {
  currentPage.value = val  // 更新当前页
}
// 初始化加载订单列表
onMounted(async () => {
  await getPurchaseOrderList()
})

// 获取订单列表
const getPurchaseOrderList = async () => {
  try {
    const res = await purchaseApi.getPurchaseOrderList()

    
    purchaseOrders.value = res
    filterOrders.value = res
    total.value = res.length  // 更新总数据量
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '获取订单列表失败')
  }
}

// 处理创建订单
const handleCreate = async () => {
  await createFormRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      await purchaseApi.createPurchaseOrder(createForm)
      ElMessage.success('采购订单创建成功')
      createDialogVisible.value = false
      createFormRef.value.resetFields()
      await getPurchaseOrderList() // 刷新列表
    } catch (err) {
      ElMessage.error(err.response?.data?.message || '创建订单失败')
    }
  })
}

// 显示审核对话框
const showApproveDialog = (id) => {
  currentOrderId.value = id
  approveDialogVisible.value = true
}

// 审核通过
const handleApprove = async () => {
  try {
    await purchaseApi.approvePurchaseOrder(currentOrderId.value)
    ElMessage.success('审核通过')
    approveDialogVisible.value = false
    await getPurchaseOrderList() // 刷新列表
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '审核失败')
  }
}

// 审核不通过
const handleReject = async () => {
  try {
    await purchaseApi.rejectPurchaseOrder(currentOrderId.value)
    ElMessage.success('审核不通过')
    approveDialogVisible.value = false
    await getPurchaseOrderList() // 刷新列表
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '审核失败')
  }
}

// 完成采购
const handleComplete = async (id) => {
  try {
    await purchaseApi.completePurchase(id)
    ElMessage.success('采购完成，已触发入库流程')
    await getPurchaseOrderList() // 刷新列表
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '完成采购失败')
  }
}
// 重新提交
const handleReSubmit = async (id) => {
  try {
    await purchaseApi.reAuditPurchaseOrder(id)
    ElMessage.success('重新提交成功')
    await getPurchaseOrderList() // 刷新列表
  } catch (err) {
    ElMessage.error(err.response?.data?.message || '重新提交失败')
  }
}
// 取消订单
const handleCancel = async (id) => {
  try {
    await purchaseApi.cancelPurchaseOrder(id)
    ElMessage.success('订单取消成功')
    await getPurchaseOrderList() // 刷新列表
  }
  catch (err) {
    ElMessage.error(err.response?.data?.message || '取消订单失败')
  }
}


// Add component name definition using defineOptions (Vue 3 feature)
defineOptions({
  name: 'PurchaseManage'
})
</script>

<style scoped>
.purchase-manage-container {
  padding: 20px;
  /* 限制表格容器最大宽度，避免过宽 */
  max-width: 1200px;
  margin: 0 auto;
}

/* 调整表格内文字对齐（可选） */
.el-table th, .el-table td {
  text-align: center;  /* 全局居中对齐 */
}
.el-table .cell {  /* 内容过长时自动换行 */
  white-space: normal;
}
.pagination-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  text-align: center; /* 水平居中 */
  margin: 20px 0; /* 调整上下边距 */
}

/* 可选：调整分页组件内间距 */
.el-pagination {
  padding: 10px 20px; /* 增加内边距使组件更饱满 */
}
.purchase-card {
  margin: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
}

.chart-action-row {
  margin-bottom: 20px;
}

.create-btn-col {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.chart-container {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}
.filter-buttons {
  margin: 0 20px;
}
.filter-buttons .el-button {
  margin: 0 4px;
}
</style>
